/* Copyright 2010 John L. Reilly

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

package com.riq;

import java.io.IOException;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.riq.entity.Department;
import com.riq.entity.Member;

@SuppressWarnings("serial")
public class CookieServlet extends HttpServlet {
	
  private static final Logger log = Logger.getLogger(CookieServlet.class.getName());
  private static final int MAX_COOKIE_AGE_MS = 60*60*24*1000;  // for cookie age
  
  private String deptId;
  private String memberId;
  private String memberHash;

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {  
    
    // ---------------------------------------------------------------------------------------------
    //  HEADER: COOKIE
    // ---------------------------------------------------------------------------------------------

    String action = request.getParameter("action"); 
    deptId = request.getParameter("deptId");
    memberId = request.getParameter("memberId");
    memberHash = request.getParameter("memberHash"); 
    
    // ---------------------------------------------------------------------------------------------
    //  METHOD DIRECTORY: COOKIE
    // ---------------------------------------------------------------------------------------------

      if ("SetPermCookies".equalsIgnoreCase(action)) { 
        SetPermCookies(response, request); 
      } else if ("SendCookieResetSMS".equalsIgnoreCase(action)) { 
        SendCookieResetSMS(response, request); 
      } else if ("demo".equalsIgnoreCase(action)) { 
        demo(response, request); 
      } else if ("deptCookie".equalsIgnoreCase(action)) { 
        deptCookie(response, request); 
      } else { response.sendRedirect("mainMenu.html"); }
      
  }

  // -----------------------------------------------------------------------------------------------
  //  METHODS: COOKIE
  // -----------------------------------------------------------------------------------------------
  
  private void SetPermCookies(HttpServletResponse response, ServletRequest request) {
    
      PersistenceManager pm = PMF.get().getPersistenceManager();
      String queryMember =  " select from " + Member.class.getName() + 
      " where cookieHash == '" + memberHash + "' ";
      // TODO: remove hardcode at launch
//      " where cookieHash == 'demo' ";
      
      List<Member> m = (List<Member>) pm.newQuery(queryMember).execute();
      String targetMemberId = m.get(0).getid().toString();
      String targetMemberCookieHash = m.get(0).getcookieHash();
      Long deptId = m.get(0).getdeptId();
      Department d = (Department) pm.getObjectById(Department.class, deptId);
            
      if (!m.isEmpty()) {

        Cookie c;
        
        c = new Cookie("cvMemberHash", targetMemberCookieHash);
        c.setMaxAge(MAX_COOKIE_AGE_MS);
        response.addCookie(c);
        
        c = new Cookie("cvMemberId", targetMemberId);
        c.setMaxAge(MAX_COOKIE_AGE_MS);
        response.addCookie(c);
        
        c = new Cookie("cvDeptId", deptId.toString());
        c.setMaxAge(MAX_COOKIE_AGE_MS);
        response.addCookie(c);
        
        c = new Cookie("cvMutualAid", d.getmutualAid());
        c.setMaxAge(MAX_COOKIE_AGE_MS);
        response.addCookie(c);
 
      }

      try {
        response.sendRedirect("mainMenu.html");
      } catch (IOException e) {
        log.info("Inside SetPermCookies caught");

        // TODO Auto-generated catch block
        e.printStackTrace();
      }
  }


  
  private void SendCookieResetSMS(HttpServletResponse response, ServletRequest request) {

    PersistenceManager pm = PMF.get().getPersistenceManager();
    Long memberIdtoReset = Long.valueOf(request.getParameter("memberId"));
    Member m = pm.getObjectById(Member.class, memberIdtoReset);

	try {
	  
		if (m.getsmsAddress().length() == 0) {
			response.sendRedirect("noSuchObject.jsp?errorMessage=noMemberSMS");
		} 
	} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
	}
	
    try {

      if (memberIdtoReset != null) {
        
        // create new hash (using memberId and timestamp as seed) for setting new cookie
        GregorianCalendar gc = new GregorianCalendar();
        String time = String.valueOf(gc.getTimeInMillis());
        String timeId = time.substring(time.length()-5, time.length());
        String newCookieHash = (3*memberIdtoReset) + "r" + timeId;
        m.setcookieHash(newCookieHash);

        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        // send link to member that will reset their browser cookie
        String msgBody = "http://responderiq05.appspot.com/c?action=SetPermCookies&memberHash=" + 
        newCookieHash + " --- " + 
        "Please copy and paste the link above into any browser " + 
        "you wish to use with FirstResponder.";

        String recipientAddress = "";
        recipientAddress = m.getsmsAddress();
        String senderAddress = "jreilly@gmail.com";

        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(senderAddress));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientAddress));

        msg.setSubject("FirstResponder Security Token");
        msg.setText(msgBody); 
        Transport.send(msg);
 
        pm.makePersistent(m);
        
      }
      
    } catch (AddressException m2) {
      // ...
    } catch (MessagingException m2) {
      // ...
    } finally {
      pm.close();
    }

    try {
      response.sendRedirect("department?action=display");
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  

  private void demo(HttpServletResponse response, ServletRequest request) {
    
    Cookie cPut = new Cookie("cvMemberId", memberId);
    cPut.setMaxAge(MAX_COOKIE_AGE_MS);
    response.addCookie(cPut);
    
    cPut = new Cookie("cvDeptId", deptId);
    cPut.setMaxAge(MAX_COOKIE_AGE_MS);
    response.addCookie(cPut);
    
    cPut = new Cookie("cvMemberHash", memberHash);
    cPut.setMaxAge(MAX_COOKIE_AGE_MS);
    response.addCookie(cPut);
    
    try {
      response.sendRedirect("/mainMenu.html");
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  
  
  private void deptCookie(HttpServletResponse response, ServletRequest request ) {

    String deptId = request.getParameter("shortName");
    if (deptId != null) {
    Cookie cPut = new Cookie("cvDeptId", deptId);
    cPut.setMaxAge(MAX_COOKIE_AGE_MS);
    response.addCookie(cPut);
    } else {
      try {
        response.sendRedirect("/noSuchObject.jsp?errorMessage=noDeptId");
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  
    try {
      response.sendRedirect("/mainMenu.html");
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  
}

